﻿// ***********************************************************************
// Assembly         : OSS.ModelViewer
// Author           : tian_
// Created          : 05-16-2018
//
// Last Modified By : tian_
// Last Modified On : 07-06-2018
// ***********************************************************************
// <copyright file="TestTexture2DCmd.cs" company="">
//     Copyright ©  2018
// </copyright>
// <summary></summary>
// ***********************************************************************
using Osg;
using ZFGK.Addins;
using ZFGK.OSG.UI;
using ZFGK.OSG.UI.Utility;
using ZFGK.OSG.Utility;
using ZFGK.Utility;
using ZFGK.WinForms.Utility;

namespace OSS.ModelViewer.Commands.TestCmds
{
    /// <summary>
    /// Class TestTexture2DCmd.
    /// </summary>
    /// <seealso cref="ZFGK.Addins.IExtendCommand" />
    public class TestTexture2DCmd : IExtendCommand
    {
        /// <summary>
        /// Executes the specified command data.
        /// </summary>
        /// <param name="cmdData">The command data.</param>
        /// <param name="message">The message.</param>
        /// <returns>CmdResult.</returns>
        public CmdResult Execute(ExtendCmdData cmdData, ref string message)
        {
            var viewForm = cmdData.ViewForm as IViewForm;
            if (viewForm == null)
                return CmdResult.Cancel;
            var osgView = viewForm.View as IOsgViewCtrl;
            // 选择贴图文件
            string filePath = null;
            if (!DialogUtil.Open("选择贴图文件", "图片(*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif", out filePath))
            {
                return CmdResult.Cancel;
            } 

            //创建一个用于保存几何信息的图像
            Geometry geom = new Geometry();
            //创建4个顶点的数组
            Vec3Array vertexArray = new Vec3Array();
            /*vArr.push_back(new Vec3d(x, y, z));
            vArr.push_back(new Vec3d(x + w, y, z));
            vArr.push_back(new Vec3d(x + w, y + h, z));
            vArr.push_back(new Vec3d(x, y + h, z));*/
            float length = 1, width = 2, xOffset = 1, /*yOffsrt = 1,*/ zOffset = 1;
            vertexArray.push_back(new Vec3f(-length + xOffset, 0.0f, -width + zOffset));
            vertexArray.push_back(new Vec3f(length + xOffset, 0.0f, -width + zOffset));
            vertexArray.push_back(new Vec3f(length + xOffset, 0.0f, width + zOffset));
            vertexArray.push_back(new Vec3f(-length + xOffset, 0.0f, width + zOffset));
            geom.setVertexArray(vertexArray);

            //由保存的数据绘制四个顶点的多边形
            geom.addPrimitiveSet(new DrawArrays((uint)PrimitiveSet.Mode.QUADS, 0, 4));

            //为法线创建数组
            Vec3Array normalArray = new Vec3Array();
            normalArray.push_back(new Vec3f(0, 1, 0));
            geom.setNormalArray(normalArray, Osg.Array.Binding.BIND_OVERALL);

            //为颜色创建数组
            Vec4Array colorArray = new Vec4Array();
            colorArray.push_back(new Vec4f(1, 1, 1, 1));
            geom.setColorArray(colorArray, Osg.Array.Binding.BIND_OVERALL);

            //为纹理创建数组
            Vec2Array texCoordArray = new Vec2Array();//创建一个 Vec2Array对象以保存纹理单元 0 的纹理坐标
            
            texCoordArray.push_back(new Vec2f(0, 0));
            texCoordArray.push_back(new Vec2f(0, 1));
            texCoordArray.push_back(new Vec2f(1, 1));
            texCoordArray.push_back(new Vec2f(1, 0));
            geom.setTexCoordArray(0, texCoordArray, Array.Binding.BIND_PER_PRIMITIVE_SET);

            //向Geode类添加几何体（Drawable）
            Geode geode = new Geode();
            geode.addDrawable(geom);

            StateSet stateSet = geode.getOrCreateStateSet();

            stateSet.setMode(GL.GL_BLEND, (uint)StateAttribute.Values.ON);
            stateSet.setMode(GL.GL_LIGHTING, (uint)StateAttribute.Values.OFF);
            stateSet.setRenderingHint((int)StateSet.RenderingHint.TRANSPARENT_BIN);

            Image image = OsgDB._.readImageFile(filePath);
            if (!image.IsValid || !image.valid())
            {
                ZfMessageUtil.ShowError("打开图像文件失败！");
                return CmdResult.Cancel;
            }

            //将图像关联到Texture 2D对象
            Texture2D texture2D = new Texture2D();
            texture2D.setImage(image);
            //texture2D.setTextureHeight();
            // 创建纹理对象后,释放内部的ref_ptr<Image>,删除Image图像。
            texture2D.setUnRefImageDataAfterApply(true);

            stateSet.setTextureAttributeAndModes(0, texture2D);//关联材质属性与模式到材质单元0

            //打开混合
            BlendFunc blendFunc = new BlendFunc((uint)Osg.BlendFunc.BlendFuncMode.SRC_ALPHA, (uint)Osg.BlendFunc.BlendFuncMode.ONE_MINUS_SRC_ALPHA);
            stateSet.setAttributeAndModes(blendFunc);

            // 打开Alpha测试
            AlphaFunc alphaFunc = new AlphaFunc(AlphaFunc.ComparisonFunction.GREATER, 0.05f);
            stateSet.setAttributeAndModes(alphaFunc);

//             var osgNode = new OsgNode("Models");
//             osgNode.AddOrReplaceModel(new NodeData("1") { Node = geode });
// 
//             osgView.AddOrReplaceModel(osgNode);

            osgView.OsgObj.AddOrReplaceModel("Models", geode, "1");

            return CmdResult.Succeed;
        }
    }
}
